import XLSX from 'xlsx-js-style'
import type { TableColumn } from '@/types'

function withBorder(array: any[]) {
  return array.map(v => ({
    v,
    t: 's',
    s: {
      border: {
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
        left: { style: 'thin' },
      },
    },
  }))
}

export function useSimpleExportLists<T = Record<string, any>>(option: {
  columns: TableColumn<T>[]
  lists: T[]
}) {
  const { columns, lists } = toValue(option)
  const cols = columns.filter(v => v.type === undefined && v.label && v.prop)
  const labels = cols.map(v => v.label)
  const props = cols.map(v => v.prop) as string[]
  const data = lists.map((v: any) => {
    return props.map(prop => v[prop])
  })
  const exportXlsx = (fileName?: string, prefixFn?: () => any[], mergesFn?: () => any[], formatCellFn?: (wb: any, ws: any, aoa: any) => void) => {
    const aoa = [...(prefixFn?.() || []), withBorder(labels), ...data.map(v => withBorder(v))]
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(aoa)

    const cs: any[] = (ws['!cols'] = [])
    const values = props.map((prop, index) => {
      const item = lists.map((v: any) => v[prop])
      item.unshift(labels[index])
      return item
    })

    values.forEach((value, index) => {
      cs[index] = { wch: Math.max(...value.map(v => String(v).length), 10) }
    })

    ws['!merges'] = mergesFn?.() || []

    if (formatCellFn) {
      try {
        formatCellFn(wb, ws, aoa)
      }
      catch (e) {}
    }

    XLSX.utils.book_append_sheet(wb, ws, fileName || 'Sheet1')
    XLSX.writeFile(wb, `${fileName || '导出数据'}.xlsx`, { compression: true })
  }
  return {
    exportXlsx,
  }
}
